﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Globalization;

namespace MetaCollection.Framework.Repository
{
	public class AdoNetAudit : IAuditRepository
	{
		private string m_ConnectionString;
		private bool m_Initialized;


		private void EnsureInitialized()
		{
			if (!m_Initialized)
				throw new InvalidOperationException("Event Provider must be initialized prior to use.");
		}

		#region IEventRepository Members

		public void Initialize(string configData)
		{
			m_ConnectionString = configData;
			m_Initialized = true;
		}

		public IEnumerable<MetaCollection.Framework.Model.IItemAudit> GetItemEvents(MetaCollection.Framework.Model.IItemInstance item)
		{
			throw new NotImplementedException();
			//EnsureInitialized();

			//if (item == null)
			//    throw new ArgumentNullException("Item cannot be null.");

			//string query = String.Format(CultureInfo.InvariantCulture, @"SELECT {0} FROM structure.Item inner join structure.ItemVersion on Item.Id = ItemVersion.ItemId WHERE ItemId = @id", GetSelectColumns(opt));
			//Dictionary<string, object> parameters = new Dictionary<string, object>();
			//parameters.Add("@id", id);
		}

		public void SaveItemEvent(MetaCollection.Framework.Model.IItemInstance item, string eventType, string message)
		{
			EnsureInitialized();

			if (item == null)
				throw new ArgumentNullException("item", "Item cannot be null.");

			using (SqlConnection sqlConn = new SqlConnection(m_ConnectionString))
			{
				sqlConn.Open();
				using (SqlCommand writeData = 
					new SqlCommand("INSERT INTO structure.ItemEvent ([ItemId], [Version], [EventDate], [EventType], [Message]) VALUES (@itemId, @version, @eventDate, @eventType, @message)", 
						sqlConn))
				{
					writeData.Parameters.AddWithValue("@itemId", item.Id);
					writeData.Parameters.AddWithValue("@version", item.Version);
					writeData.Parameters.AddWithValue("@eventDate", DateTime.Now);
					writeData.Parameters.AddWithValue("@eventType", eventType);
					writeData.Parameters.AddWithValue("@message", message);
					writeData.ExecuteNonQuery();
				}
			}
		}

		#endregion
	}
}
